/*
 * Programmer	:	Baljeet Singh
 * Project	 	:  	Travel Experts Phase 3 (Package Management)
 * Language  	:  	Java
 * Date Written	:   March 3, 2011.
 * Student Id	:	562632	
 */

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.toedter.calendar.JDateChooser;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class PackagePanel extends javax.swing.JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	//variables declared below
	private JScrollPane jScrollPane1;
	private JButton btnAdd;
	private JButton btnSuppProd;
	private JLabel lblPkgDesc;
	private JButton btnSave;
	private JButton btnClear;
	private JTextArea txtPkgDesc;
	private JTextField txtPkgAgComm;
	private JTextField txtPkgBasePrice;
	private JLabel lblPkgAgComm;
	private JLabel lblPkgBasePrice;
	private JLabel lblPkgEndDate;
	private JTextField txtPkgId;
	private JTextField txtPkgName;
	private JLabel lblpkgStartDate;
	private JLabel lblPkgName;
	private JLabel lblPkgId;
	private JButton btnDelete;
	private JButton btnEdit;
	private JTable tblPackages;
	private JLabel jLabel2;
	private JLabel jLabel1;
	private JDateChooser startdate_ch;
	private JDateChooser enddate_ch;
	private static Statement stmt;
	private boolean Add = false;
	private boolean Clear=false;
	private boolean Update = false;
	private ResultSet rs;
	DefaultTableModel tblPackagesModel = new DefaultTableModel();
	JDialog d = new JDialog();
	
	
	public static void main(String[] args) 
	{
		JFrame frame = new JFrame();
		frame.getContentPane().add(new PackagePanel());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public PackagePanel() 
	{
		super();
		initGUI();
		//instantiate the productsupplierdialog 
		//psDlg=new ProdSuppDialog(PackagePanel.this,txtPkgId.getText());

		try
		{
			//call the method to load the table with packages
			loadtable();
		} 
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//Code to draw the Package Management GUI
	private void initGUI() 
	{
		try 
		{
			this.setPreferredSize(new java.awt.Dimension(999, 590));
			this.setLayout(null);
			{
				jLabel1 = new JLabel();
				this.add(jLabel1);
				jLabel1.setText("Packages Management");
				jLabel1.setFont(new java.awt.Font("Segoe UI",1,20));
				jLabel1.setBounds(403, 5, 277, 55);
			}
			{
				jLabel2 = new JLabel();
				this.add(jLabel2);
				jLabel2.setText("Packages");
				jLabel2.setBounds(30, 60, 102, 26);
				jLabel2.setFont(new java.awt.Font("Arial Narrow",1,18));
			}
			{
				jScrollPane1 = new JScrollPane();
				this.add(jScrollPane1);
				jScrollPane1.setBounds(18, 86, 952, 165);
				{
					
					tblPackages = new JTable();
					jScrollPane1.setViewportView(tblPackages);
					tblPackages.setModel(tblPackagesModel);
					tblPackages.setBounds(50, 107, 674, 111);
					tblPackagesModel.setColumnCount(7);
					tblPackages.addKeyListener(new KeyListener() {
						
						@Override
						public void keyTyped(KeyEvent e)
						{
							// TODO Auto-generated method stub
						}
						
						@Override
						public void keyReleased(KeyEvent e) 
						{
							// TODO Auto-generated method stub
						}
						//code to handle the up and down arrow keys event 
						@Override
						public void keyPressed(KeyEvent e)
						{
							// TODO Auto-generated method stub
							//populating the fields on the form when the down or up arrow key is pressed
								if(e.getKeyCode()==KeyEvent.VK_DOWN)
								{
									
									if(tblPackagesModel.getRowCount()>tblPackages.getSelectedRow()+1)
									{
										populateForm(tblPackages.getSelectedRow()+1);
									}
								}
								if(e.getKeyCode()==KeyEvent.VK_UP) 
								{
									if(tblPackages.getSelectedRow()==0)
									{
										return;
									}
									if(tblPackages.getSelectedRow() <= tblPackagesModel.getRowCount()-1)
									{
										populateForm(tblPackages.getSelectedRow()-1);
									}
									
								}
								else
								{
									return;
								}
						}

						
					});
					tblPackages.addMouseListener(new MouseAdapter() {
						//code to handle mouse click event on supplier table
						@Override
						public void mouseClicked(MouseEvent e) 
						{
							// TODO Auto-generated method stub
							super.mouseClicked(e);
							populateForm(tblPackages.getSelectedRow());
						}
					});
				    
				}
			}
			{
				btnAdd = new JButton();
				this.add(btnAdd);
				btnAdd.setText("Add");
				btnAdd.setBounds(65, 263, 104, 46);
				btnAdd.addMouseListener(new MouseAdapter() {
					//code for handling the mouse click on Add button
					@Override
					public void mouseClicked(MouseEvent e) 
					{
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						try 
						{
							//refresh the table
							loadtable();
						}
						catch (SQLException e1) 
						{
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						Add=true;
						//populate the form fields 
						populateForm(tblPackages.getSelectedRow());
						Clear=true;
					}
				});
			}
			{
				btnEdit = new JButton();
				this.add(btnEdit);
				btnEdit.setText("Edit");
				btnEdit.setBounds(318, 263, 110, 45);
				btnEdit.addMouseListener(new MouseAdapter() {
					//code for handling the mouse click on Edit button
					@Override
					public void mouseClicked(MouseEvent e)
					{
						super.mouseClicked(e);
						// TODO Auto-generated method stub
						//check to see if the table has some row
						if(tblPackages.getRowCount()==0)
						{
							JOptionPane.showMessageDialog(PackagePanel.this, "Nothing in Table to Update", "Error", JOptionPane.ERROR_MESSAGE);
						}
						//check to see if package is selected to update
						else if(tblPackages.getSelectedRow()==-1)
						{
							JOptionPane.showMessageDialog(PackagePanel.this, "Please select a package to Update","Error", JOptionPane.ERROR_MESSAGE);
						}
						else
						{
							Update=true;
							//populate the form accordingly
							populateForm(tblPackages.getSelectedRow());
						}
						
						
					}
				});
				
				
			}
			{
				btnDelete = new JButton();
				this.add(btnDelete);
				btnDelete.setText("Delete");
				btnDelete.setBounds(797, 262, 105, 46);
				btnDelete.addMouseListener(new MouseAdapter() {
					//code for handling the mouse click on Delete button
					@Override
					public void mouseClicked(MouseEvent e) {
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						//check to see if the table has data
						if(tblPackages.getRowCount()==0)
						{
							JOptionPane.showMessageDialog(PackagePanel.this, "Nothing in Table to Delete", "Error", JOptionPane.ERROR_MESSAGE);
						}
						//check to see if a package is selected
						else if(tblPackages.getSelectedRow()==-1)
						{
							JOptionPane.showMessageDialog(PackagePanel.this, "Please select a package to delete", "Error", JOptionPane.ERROR_MESSAGE);
						}
						else
						{
							//confirm before delete
							int i = JOptionPane.showConfirmDialog(PackagePanel.this, "Do you really want to delete "+txtPkgName.getText()+" from the list of available packages?");
							if(i==0)
							{
								//if yes then delete
								Database_Functions.databaseConnection();
								try 
								{
									stmt.executeUpdate("delete from Packages where PackageId="+txtPkgId.getText());
									//clear the form fields and refresh the table
									clearFields();
									loadtable();
								} 
								catch (SQLException e1) 
								{
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
							}
						}
					}
				});
			}
			{
				lblPkgId = new JLabel();
				this.add(lblPkgId);
				lblPkgId.setText("Package ID");
				lblPkgId.setBounds(75, 330, 81, 22);
			}
			{
				lblPkgName = new JLabel();
				this.add(lblPkgName);
				lblPkgName.setText("Package Name");
				lblPkgName.setBounds(75, 368, 99, 24);
			}
			{
				lblpkgStartDate = new JLabel();
				this.add(lblpkgStartDate);
				lblpkgStartDate.setText("Package Start Date");
				lblpkgStartDate.setBounds(75, 411, 131, 22);
			}
			{
				txtPkgId = new JTextField();
				this.add(txtPkgId);
				txtPkgId.setBounds(252, 330, 201, 23);
			}
			{
				startdate_ch = new JDateChooser();
				this.add(startdate_ch);
				startdate_ch.setBounds(252, 411, 201, 23);
			}
			{
				enddate_ch = new JDateChooser();
				this.add(enddate_ch);
				enddate_ch.setBounds(729, 327, 192, 23);
			}
			{
				txtPkgName = new JTextField();
				this.add(txtPkgName);
				txtPkgName.setBounds(252, 369, 201, 23);
			}
			{
				lblPkgEndDate = new JLabel();
				this.add(lblPkgEndDate);
				lblPkgEndDate.setText("Package End Date");
				lblPkgEndDate.setBounds(498, 331, 128, 20);
			}
			{
				lblPkgBasePrice = new JLabel();
				this.add(lblPkgBasePrice);
				lblPkgBasePrice.setText("Package Base Price");
				lblPkgBasePrice.setBounds(498, 363, 134, 34);
			}
			{
				lblPkgAgComm = new JLabel();
				this.add(lblPkgAgComm);
				lblPkgAgComm.setText("Package Agency Commission");
				lblPkgAgComm.setBounds(498, 411, 192, 22);
			}
			{
				txtPkgBasePrice = new JTextField();
				this.add(txtPkgBasePrice);
				txtPkgBasePrice.setBounds(729, 369, 192, 23);
			}
			{
				txtPkgAgComm = new JTextField();
				this.add(txtPkgAgComm);
				txtPkgAgComm.setBounds(729, 411, 192, 23);
			}
			{
				lblPkgDesc = new JLabel();
				this.add(lblPkgDesc);
				lblPkgDesc.setText("Package Description");
				lblPkgDesc.setBounds(75, 457, 143, 27);
			}
			{
				txtPkgDesc = new JTextArea();
				this.add(txtPkgDesc);
				txtPkgDesc.setBounds(256, 464, 665, 38);
			}
			{
				btnClear = new JButton();
				this.add(btnClear);
				btnClear.setText("Clear");
				btnClear.setBounds(571, 263, 109, 45);
				btnClear.addMouseListener(new MouseAdapter() {
					//code for handling the mouse click on Clear button
					@Override
					public void mouseClicked(MouseEvent e) 
					{
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						if(btnClear.isEnabled()==false)
						{
							return;
						}
						//call the clearfields function
						clearFields();						
					}
				});
			}
			{
				btnSave = new JButton();
				this.add(btnSave);
				btnSave.setText("Save");
				btnSave.setBounds(256, 519, 263, 40);
				btnSave.addMouseListener(new MouseAdapter() {
					//code for handling the mouse click on Save button
					@Override
					public void mouseClicked(MouseEvent e)
					{
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						if(btnSave.isEnabled()==false)
						{
							return;
						}
						Database_Functions.databaseConnection();
						try
						{
							//validate before insert or update
							if(!validation())
							{
								//if not valid the return from the function
								return;
							}
							else
							{
								//if valid then get the dates from the date timepickers 
								Calendar start= startdate_ch.getCalendar();
								Calendar end = enddate_ch.getCalendar();
								java.sql.Date start_date=new Date(start.getTimeInMillis());
								java.sql.Date end_date= new Date(end.getTimeInMillis());
								String strSQL="";
								if(Clear)
								{
									 
									 strSQL = "Insert Into Packages (PackageId, PkgName, PkgStartDate, PkgEndDate, PkgDesc, PkgBasePrice, PkgAgencyCommission)" 
											+ "Values(S_112_1_PACKAGES.nextval, '"+txtPkgName.getText()+"', '"+start_date+"', '"
											+end_date+"', '"+txtPkgDesc.getText()+"', "+txtPkgBasePrice.getText()+", "+txtPkgAgComm.getText()+")";
									Clear=false;
								}
								else
								{
									 strSQL="Update Packages set PkgName='"+txtPkgName.getText()
											+"', PkgStartDate='"+start_date+"', PkgEndDate='"+end_date+"', PkgDesc='"+txtPkgDesc.getText()
											+"', PkgBasePrice="+txtPkgBasePrice.getText()+", PkgAgencyCommission="+txtPkgAgComm.getText()
											+" where PackageId="+txtPkgId.getText();
								}
								stmt.executeUpdate(strSQL);
								//refresh the table
								loadtable();
								clearFields();
							}
						} 
						catch (SQLException e1) 
						{
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				});
			}
			{
				btnSuppProd = new JButton();
				this.add(btnSuppProd);
				btnSuppProd.setText("Suppliers and Products");
				btnSuppProd.setBounds(612, 519, 251, 39);
				btnSuppProd.addMouseListener(new MouseAdapter() 
				{
					@Override
					//code for handling the mouse click on productsupplier button
					public void mouseClicked(MouseEvent e) {
						// TODO Auto-generated method stub
						super.mouseClicked(e);
						if(txtPkgId.getText().equals(""))
						{
							JOptionPane.showMessageDialog(PackagePanel.this, "Please select a package ", "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}
						else
						{
							ProdSuppDialog psDlg=new ProdSuppDialog(PackagePanel.this, PackagePanel.this.txtPkgId.getText());;
							psDlg.setModal(true);
							psDlg.setVisible(true);
						}
				}
				});
			}
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	//function to validate the input
	public boolean validation()
	{
		//check if the package name is entered or not
		if(txtPkgName.getText().equals(""))
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter the name of the package");
			return false;
		}
		//check if the startdate is entered or not 
		else if(startdate_ch.getDate()==null)
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter the start date of the package");
			return false;
		}
		//check if the enddate is entered or not
		else if(enddate_ch.getDate()==null)
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter the end date of the package");
			return false;
		}
		//check if the startdate is greater than enddate
		else if(enddate_ch.getDate().compareTo(startdate_ch.getDate())<0)
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "End Date of package must be greater than the start date");
			return false;
		}
		//check if the baseprice is entered or not
		else if(txtPkgBasePrice.getText().equals(""))
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter the Base price of the package");
			return false;
		}
		//check if the baseprice is numeric or not
		String expression = "\\d+(\\.\\d{1,4})?";  
	    Pattern pattern = Pattern.compile(expression);  
		Matcher matcher1 = pattern.matcher(txtPkgBasePrice.getText());  
		if(matcher1.matches()==false)
		{  
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter numeric value for Base price");
		    return false;            
		} 
		//check if the AgencyCommission is entered or not
		if(txtPkgAgComm.getText().equals(""))
		{
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter the Agency Commission of the package");
			return false;
		}
		Matcher matcher2 = pattern.matcher(txtPkgAgComm.getText());
		//check if the AgencyCommission is numeric or not
		if((matcher2.matches()==false))
		{  
			JOptionPane.showMessageDialog(PackagePanel.this, "Enter numeric value for Agency Commission");
		    return false;          
		}            
		//check if the baseprice is less than AgencyCommission
		if((Double.parseDouble(txtPkgAgComm.getText()))>(Double.parseDouble(txtPkgBasePrice.getText()))) 
		{
			
				JOptionPane.showMessageDialog(PackagePanel.this, "Agency Commission cannot be greater than base price");
				return false;
			
		}
		return true;
	}
	
	//function to populate the from fields
	public void populateForm(int row) 
	{
		if(Update)
		{
			//if update is pressed than enable the form fields
			enableFields();
			Update=false;
		}
		
		else if(Add)
		{
			//if add is pressed than enable the form fields and clear them
			enableFields();
			btnClear.setEnabled(true);
			clearFields();
			Add=false;
			return;
		}
		
		else
		{
			disableFields();
		}
		// TODO Auto-generated method stub
		
		String [] fields=new String[tblPackages.getColumnCount()];
		Clear=false;
		for(int i=0;i<tblPackages.getColumnCount();i++)
		{
			fields[i]=""+tblPackagesModel.getValueAt(row, i);
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
		java.util.Date for_start =null;
		java.util.Date for_end = null;
		
		
			try 
			{
				//parsing the startdate and enddate to above defined format
				if(!fields[2].equals("null"))
				{
					for_start=df.parse(fields[2]);
				}
				if(!fields[3].equals("null"))
				{
					for_end=df.parse(fields[3]);
				}
				txtPkgId.setText(fields[0]);
				txtPkgName.setText(fields[1]);
				startdate_ch.setDate(for_start);
				enddate_ch.setDate(for_end);
				txtPkgDesc.setText(fields[4]);
				txtPkgBasePrice.setText(fields[5]);
				txtPkgAgComm.setText(fields[6]);
				
			} 
			catch (ParseException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		
	}	
	//Function that loads the table with the packages from the database
	public void loadtable() throws SQLException
	{
		//clear the table first
		 while (tblPackages.getRowCount() > 0)
		 {
			  ((DefaultTableModel)tblPackages.getModel()).removeRow(0);
		 }
		 //connect to database
		stmt=Database_Functions.databaseConnection();
		//execute the select statement to get the packages from database
		rs= Database_Functions.selectQuery("packages", "packageid","","");
		ResultSetMetaData rsmd = rs.getMetaData();
		String [] header=new String[rsmd.getColumnCount()];
		for(int j=1;j<=rsmd.getColumnCount();j++)
		{
			header[j-1]=rsmd.getColumnLabel(j);
		}
		while(rs.next())
		{
			
			Object [] myP = {rs.getInt(1),rs.getString(2),rs.getDate(3),rs.getDate(4),rs.getString(5),rs.getBigDecimal(6),rs.getBigDecimal(7)};
			tblPackagesModel.addRow(myP);
		}
		
		//code to display the header names in the table
		Enumeration<TableColumn> cols = tblPackages.getColumnModel().getColumns();
		int i=0;
		while (cols.hasMoreElements())
		{
			TableColumn col = cols.nextElement();
			col.setHeaderValue(header[i++]);
		}
		
		//disable the fields in the form and close the connection to database
		disableFields();
		
	}
	
	//Function to enable the fields on the form
	public void enableFields()
	{
		txtPkgId.setEnabled(false);
		txtPkgAgComm.setEnabled(true);
		txtPkgBasePrice.setEnabled(true);
		txtPkgDesc.setEnabled(true);
		txtPkgName.setEnabled(true);
		startdate_ch.setEnabled(true);
		enddate_ch.setEnabled(true);
		btnSave.setEnabled(true);
	}
	
	//Function to disable the fields on the form
	public void disableFields()
	{
		txtPkgId.setEnabled(false);
		txtPkgAgComm.setEnabled(false);
		txtPkgBasePrice.setEnabled(false);
		txtPkgDesc.setEnabled(false);
		txtPkgName.setEnabled(false);
		startdate_ch.setEnabled(false);
		enddate_ch.setEnabled(false);
		btnSave.setEnabled(false);
		btnClear.setEnabled(false);
	}
	
	//Function that clears the fields on the form
	public void clearFields()
	{
		txtPkgId.setText("");
		txtPkgName.setText("");
		startdate_ch.setDate(null);
		enddate_ch.setDate(null);
		txtPkgDesc.setText("");
		txtPkgBasePrice.setText("");
		txtPkgAgComm.setText("");	
	}
}
